package com.coffee.attachment.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.coffee.attachment.entity.ExcelEntity;
import com.coffee.attachment.entity.ExcelFieldEntity;
import com.coffee.attachment.repository.MochaExcelFieldRepository;
import com.coffee.attachment.repository.MochaExcelRepository;
import com.coffee.excel.MochaExcelSheet;
import com.coffee.excel.metadata.MochaExcelField;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: songkui
 * @since: 2023/4/20 14:38
 */
@Service
@Slf4j
@AllArgsConstructor
public class MochaExcelService {
    private final MochaExcelRepository mochaExcelRepository;
    private final MochaExcelFieldRepository mochaExcelFieldRepository;

    /**
     * 通过excel 编码；  和需要导出的字段 组装 成 MochaExcelField
     * @param excelCode
     * @param fields  多个逗号隔开
     * @return
     */
    public MochaExcelSheet findExcelField(String excelCode, String fields){
        Assert.hasLength(excelCode, "Query MochaExcelField excelCode is null");

        ExcelEntity entity = mochaExcelRepository.getByCode(excelCode);
        if (null == entity){
            log.info("ExcelCode {} Query ExcelEntity  is null", excelCode);
            return null;
        }
        List<ExcelFieldEntity> list = mochaExcelFieldRepository.findByExcelId(entity.getId());
        if (CollectionUtil.isEmpty(list)){
            log.info("ExcelCode {} Query ExcelFieldEntity list  is null", excelCode);
            return null;
        }

        List<MochaExcelField> fieldList = StrUtil.isEmpty(fields)
                             ? list.stream().map(this::toExcelField).collect(Collectors.toList())
                             : list.stream().filter(f -> fields.contains(f.getFieldValue())).map(this::toExcelField).collect(Collectors.toList());

        if (CollectionUtil.isEmpty(fieldList)){
            return null;
        }

        MochaExcelSheet sheet = new MochaExcelSheet();
        sheet.setTitle(entity.getTitle());
        sheet.setExcelType(entity.getExcelType());
        sheet.setFieldList(fieldList);

        return sheet;

    }


    private MochaExcelField toExcelField(ExcelFieldEntity entity){

        MochaExcelField field = new MochaExcelField();
        field.setFieldSort(entity.getFieldSort());
        field.setForegroundColor(entity.getForegroundColor());
        field.setRequiredType(entity.getRequiredType());
        field.setFieldValue(entity.getFieldValue());
        field.setHeadShow(entity.getHeadShow());

        return field;

    }


}
